/*
 * @Author: your name
 * @Date: 2021-06-07 19:45:39
 * @LastEditTime: 2021-06-09 09:48:40
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \UDP\extra.cpp
 */
//接收是否成功
		bool recv_ok;

		char send_buf[100];
		int send_length;

		char recv_buf[100];
		int recv_length = 100;


		printf("Please input msg:");
		scanf("%s",send_buf);//从键盘输入获取要发送的消息
        send_length = sizeof(send_length);
		//发送信息
		recv_ok = client.send_To_Server(send_buf,send_length,recv_buf,recv_length);

		//接收成功处理
		if(recv_ok)
		{
			cout << "length:" << recv_length << "  buf:";
			for(int i=0; i<recv_length; i++)
			{
				cout << recv_buf[i];
			}
			cout << endl;
		}
		else
		{
			cout << "服务器请求失败......" << endl;
		}

------------------------------------------------------------------------------------

/*
 * @Author: your name
 * @Date: 2021-06-06 22:16:21
 * @LastEditTime: 2021-06-08 11:15:14
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \CPP\UDP\server.cpp
 */
#include<iostream>
using namespace std;

#include <stdio.h>
#include <sys/types.h>          
#include <sys/socket.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include "parse.h"
 
 
int main(int argc,char *argv[])
{
	//判断命令行参数是否满足
	if(argc != 2)
	{
		printf("请传递一个端口号\n");
		return -1;
	}
 
	//将接收端口号并转换为int
	int port = atoi(argv[1]);
	if( port<1025 || port>65535 )//0~1024一般给系统使用，一共可以分配到65535
	{
		printf("端口号范围应为1025~65535");
		return -1;
	}
	
	// 1.创建udp通信socket  
	int udp_socket_fd = socket(AF_INET,SOCK_DGRAM,0);
	if(udp_socket_fd < 0 )
	{
		perror("creat socket fail\n");
		return -1;
	}
 
	//2.设置UDP的地址并绑定 
	struct sockaddr_in  local_addr = {0};
	local_addr.sin_family  = AF_INET; //使用IPv4协议
	local_addr.sin_port	= htons(port);   //网络通信都使用大端格式
	local_addr.sin_addr.s_addr = INADDR_ANY;//让系统检测本地网卡，自动绑定本地IP
 
	int ret = bind(udp_socket_fd,(struct sockaddr*)&local_addr,sizeof(local_addr));
	if(ret < 0)
	{
		perror("bind fail:");
		close(udp_socket_fd);
		return -1;
	}
	else
	{
		printf("recv ready!!!\n");
	}
	
 
	struct sockaddr_in  src_addr = {0};  //用来存放对方(信息的发送方)的IP地址信息
	socklen_t len = sizeof(src_addr);	//地址信息的大小
	char buf[1024] = {0};//消息缓冲区

	//创建解析报文Parse对象
	Parse _parse;
	
	//3 循环接收客户发送过来的数据  
	while(1)
	{
		ret = recvfrom(udp_socket_fd, buf, sizeof(buf), 0, (struct sockaddr *)&src_addr, &len);
		if(ret == -1)
		{
			break;
		}
		printf("[%s:%d]",inet_ntoa(src_addr.sin_addr),ntohs(src_addr.sin_port));//打印消息发送方的ip与端口号
		printf("buf=%s\n",buf);
		if(strcmp(buf, "exit") == 0)
		{
			break;
		}

		_parse.parse_Message(buf);

		char send_buf[100] = "hello";
		int send_length = 3;
		cout << "回复hello" << endl;
		//回应消息
		// len = sizeof(src_addr);
		sendto(udp_socket_fd, send_buf, send_length, 0, (struct sockaddr *)&src_addr, sizeof(src_addr)); 
		memset(buf, 0, sizeof(buf));//清空存留消息
 
	}
	
	//4 关闭通信socket
	close(udp_socket_fd);
}